import Vue from 'vue'
import VueRouter from 'vue-router'
import { Dialog } from 'vant'
import store from '../store'

// 路由懒加载；默认加载目录下的index.vue文件，可省略
const Login = () => import('../views/login/')

Vue.use(VueRouter)

const routes = [
  {
    name: 'login',
    path: '/login',
    component: Login,
    meta: { requireAuth: false } // 额外添加的自定义数据
  },
  {
    path: '/',
    redirect: '/home',
    component: () => import('../views/layout/'),
    children: [
      {
        name: 'home',
        path: '/home', // 默认子路由
        component: () => import('../views/home/'),
        meta: { requireAuth: false }
      },
      {
        name: 'my',
        path: '/my',
        component: () => import('../views/my/'),
        meta: { requireAuth: false }
      },
      {
        name: 'qa',
        path: '/qa',
        component: () => import('../views/qa/'),
        meta: { requireAuth: false }
      },
      {
        name: 'video',
        path: '/video',
        component: () => import('../views/video/'),
        meta: { requireAuth: false }
      }
    ]
  },
  {
    name: 'search',
    path: '/search',
    component: () => import('../views/search/'),
    meta: { requireAuth: false }
  },
  {
    name: 'article',
    path: '/article/:articleId',
    component: () => import('../views/article/'),
    props: true, // 将参数传入props
    meta: { requireAuth: false }
  },
  {
    name: 'profile',
    path: '/profile',
    component: () => import('../views/profile/'),
    meta: { requireAuth: false }
  },
  {
    name: 'chat',
    path: '/chat',
    component: () => import('../views/chat'),
    meta: { requireAuth: true }
  }
]

const router = new VueRouter({
  routes
})

/*
  to: 要访问的页面路由信息
  from: 来自哪个页面的路由信息
  next：放行的标记
 */
router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {
    // 需要权限
    if (store.state.user) {
      // 拥有权限
      return next()
    } else {
      // 没有权限，提示登录
      Dialog.confirm({
        title: '访问提示',
        message: '该功能需要登录才能访问，确认登录吗？'
      }).then(() => {
        router.replace({
          name: 'login',
          query: {
            returnUrl: router.currentRoute.fullPath
          }
        })
      }).catch(() => {
        // 拒绝登录，中断路由导航给
        next(false)
      })
    }
  } else {
    // 不需要权限
    next()
  }
})

export default router
